﻿@{
    ViewData["Title"] = "RoomMaintenanceView";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="layui-form layui-form-pane">
    <div>
        <div class="layui-inline">
            <div class="layui-input-inline">
                <input type="text" class="layui-input" id="datePicker">
            </div>
        </div>
        @*         <div class="layui-inline">
        <div style="margin-left:30px">
        <button type="button" id="btnOpen" class="layui-btn layui-btn-primary layui-border-blue">批量调整房态</button>
        </div>
        </div> *@
        <div class="layui-inline">
            <div style="margin-left:700px">
                <button type="button" id="btnOpen" class="layui-btn layui-btn-primary layui-border-blue" onclick="window.location.reload();">刷新</button>
            </div>
        </div>
    </div>
</div>


@* 显示 *@
<table class="layui-table" id="demoTable" lay-filter="demoTable">
    <tbody>
    </tbody>
</table>

<div id="HousingState" style="display: none;">
    <div style="margin-top:20px">
        <form class="layui-form" lay-filter="adjustForm">
            <div class="layui-form-item">
                <label class="layui-form-label">产品名称</label>
                <label class="layui-form-label" name="productsName"></label>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">生效日期</label>
                <label class="layui-form-label" name="effectivedate"></label>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">设置房态</label>
                <div class="layui-input-block">
                    <input type="radio" name="setRoomStatus" value="1" title="维持不变" checked>
                    <input type="radio" name="setRoomStatus" value="2" title="设置开房">
                    <input type="radio" name="setRoomStatus" value="3" title="设置关房">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">剩余房量</label>
                <div class="layui-input-block">
                    <table>
                        <tr>
                            <td>
                                <input type="radio" name="State" value="1" title="不做修改" checked>
                            </td>
                        </tr>
                    </table>
                    <table>
                        <tr>
                            <td>
                                <input type="radio" name="State" value="2" title="设为" lay-filter="radior">
                            </td>
                            <td style="width:80px">
                                <input type="text" name="residueNum" value="0" disabled style="height:30px" autocomplete="off" class="layui-input">
                            </td>
                            <td>
                                <label style="margin-left:10px">间</label>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="affirm">确认</button>
                    <button type="button" class="layui-btn layui-btn-primary" lay-on="closeFormBtn">取消</button>
                    <input type="text" style="display:none" name="priceCalendarId">
                </div>
            </div>
        </form>
    </div>
</div>
@* <script src="~/rooms/roommaintenance.js"></script> *@
<script>
    layui.use(['table', 'form', 'layer', 'jquery', 'laydate', 'tree',], function () {
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.jquery;
        var table = layui.table;
        var laydate = layui.laydate;

        // laydate 初始化
        laydate.render({
            elem: '#datePicker', // 绑定元素
            value: getCurrentDate(), // 设置默认值
            done: function (value, date) { // 监听日期选择完毕
                // 将选择的日期赋值给 #datenow 元素的值
                $('#datePicker').val(value);
                console.log($('#datePicker').val())
                // 重新加载数据
                show();
            }
        });

        //选中单选框启用文本框
        form.on('radio(radior)', function (data) {
            $('input[type="text"][name=residueNum]').prop('disabled', true);

            // 根据选中的单选框启用对应的文本框
            if (data.value === '2') {
                $('[name=residueNum]').prop('disabled', false);
            }
            // 执行layui表单的重新渲染，以更新样式
            layui.form.render();
        });

        $(document).ready(function () {
            // 初始加载数据
            show();
        });

        function mergeSameRows(data) {
            var mergedData = [];
            var prevRow = null;
            data.forEach(function (currentRow) {
                if (prevRow &&
                    prevRow.housingPricesId === currentRow.housingPricesId &&
                    prevRow.roomId === currentRow.roomId &&
                    prevRow.roomName === currentRow.roomName &&
                    prevRow.productsName === currentRow.productsName) {
                    prevRow.data.push({
                        priceCalendarId: currentRow.priceCalendarId,
                        residueNum: currentRow.residueNum,
                        priceEveryDate: currentRow.priceEveryDate,
                        addTime: currentRow.addTime,
                    });
                } else {
                    if (prevRow !== null) {
                        mergedData.push(prevRow);
                    }
                    prevRow = {
                        housingPricesId: currentRow.housingPricesId,
                        roomId: currentRow.roomId,
                        roomName: currentRow.roomName,
                        productsName: currentRow.productsName,
                        otherFields: {
                            canBook: currentRow.canBook,
                            maxCapacity: currentRow.maxCapacity,

                        },
                        data: [{
                            priceCalendarId: currentRow.priceCalendarId,
                            residueNum: currentRow.residueNum,
                            priceEveryDate: currentRow.priceEveryDate,
                            addTime: currentRow.addTime,
                        }]
                    };
                }
            });

            // 将最后一行加入到合并后的数据中
            if (prevRow !== null) {
                mergedData.push(prevRow);
            }

            return mergedData;
        }

        function show() {
            // 获取显示值
            var selectedDate = $('#datePicker').val();

            // 发送 POST 请求获取数据
            $.post({
                url: 'http://localhost:5174/api/RoomHousingState/GetRoomMaintenanceList',
                contentType: "application/json",
                data: JSON.stringify({ date: selectedDate }),
                headers: {
                    "Authorization": "Bearer " + localStorage.getItem('token')
                },
                async: true,
                success: function (res) {
                    console.log(res.data)
                    var mergedData = mergeSameRows(res.data);

                    // 获取接下来10天的日期及星期几
                    var dates = [];
                    for (var i = 0; i < 10; i++) {
                        var tempDate = new Date(selectedDate);
                        tempDate.setDate(tempDate.getDate() + i);
                        var formattedDate = formatDate(tempDate) + ' ' + getWeekday(tempDate);
                        dates.push(formattedDate);
                    }

                    // 生成表格列的定义
                    var tableCols = [
                        { field: 'roomName', title: '房型', width: 150 },
                        { field: 'productsName', title: '产品名称', width: 150 }
                    ];

                    var numbersInEnglish = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];

                    // 动态添加日期相关列
                    dates.forEach(function (date, index) {
                        console.log(date)
                        console.log(index)
                        var column = {
                            title: date,
                            width: 150,
                            event: numbersInEnglish[index],
                            templet: function (d) {
                                console.log(d)
                                var dataIndex = index;
                                var dataForDate = d.data[dataIndex];
                                if (dataForDate) {
                                    // 返回当前日期的数据
                                    return '余' + dataForDate.residueNum + '间/售' + 0 + '间<br>￥' + dataForDate.priceEveryDate +
                                        `<input type="text" style="display:none" value="${dataForDate.addTime}">`;
                                } else {
                                    return '';
                                }
                            }
                        };
                        tableCols.push(column);
                    });

                    // 渲染表格数据
                    layui.use('table', function () {
                        var table = layui.table;
                        table.render({
                            elem: '#demoTable',
                            data: mergedData,
                            cols: [tableCols]
                        });
                    });
                },
                error: function (error) {
                    console.error(error);
                }
            });
        }


        table.on('tool(demoTable)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'one':
                case 'two':
                case 'three':
                case 'four':
                case 'five':
                case 'six':
                case 'seven':
                case 'eight':
                case 'nine':
                case 'ten':
                    popup(obj.event, data); // 传递事件类型和数据给弹出窗口处理函数
                    break;
            }

            function popup(eventType, data) {
                // 获取外部定义的弹出层内容
                var HousingState = document.getElementById('HousingState').innerHTML;

                // 弹出页面层
                layer.open({
                    type: 1,
                    title: '调整房态/房量',
                    area: ['700px', '400px'], // 宽高
                    content: HousingState,
                    success: function (layero, index) {
                        $("[name=productsName]").html(data.productsName); // 使用传入的数据
                        switch (eventType) {
                            case 'one':
                                $("[name=effectivedate]").html((data.data[0].addTime).substring(0, 10));
                                $("[name=priceCalendarId]").val((data.data[0].priceCalendarId));
                                break;
                            case 'two':
                                $("[name=effectivedate]").html(data.data[1].addTime.substring(0, 10));
                                $("[name=priceCalendarId]").val((data.data[1].priceCalendarId));
                                break;
                            case 'three':
                                $("[name=effectivedate]").html(data.data[2].addTime.substring(0, 10));
                                $("[name=priceCalendarId]").val((data.data[2].priceCalendarId));
                                break;
                            case 'four':
                                $("[name=effectivedate]").html(data.data[3].addTime.substring(0, 10));
                                $("[name=priceCalendarId]").val((data.data[3].priceCalendarId));
                                break;
                            case 'five':
                                $("[name=effectivedate]").html(data.data[4].addTime.substring(0, 10));
                                $("[name=priceCalendarId]").val((data.data[4].priceCalendarId));
                                break;
                            case 'six':
                                $("[name=effectivedate]").html(data.data[5].addTime.substring(0, 10));
                                $("[name=priceCalendarId]").val((data.data[5].priceCalendarId));
                                break;
                            case 'seven':
                                $("[name=effectivedate]").html(data.data[6].addTime.substring(0, 10));
                                $("[name=priceCalendarId]").val((data.data[6].priceCalendarId));
                                break;
                            case 'eight':
                                $("[name=effectivedate]").html(data.data[7].addTime.substring(0, 10));
                                $("[name=priceCalendarId]").hvaltml((data.data[7].priceCalendarId));
                                break;
                            case 'nine':
                                $("[name=effectivedate]").html(data.data[8].addTime.substring(0, 10));
                                $("[name=priceCalendarId]").val((data.data[8].priceCalendarId));
                                break;
                            case 'ten':
                                $("[name=effectivedate]").html(data.data[9].addTime.substring(0, 10));
                                $("[name=priceCalendarId]").val((data.data[9].priceCalendarId));
                                break;
                            default:
                                $("[name=effectivedate]").html(''); // 其他情况的处理
                                $("[name=priceCalendarId]").val(''); // 其他情况的处理
                                break;
                        }

                        form.render();

                        // 表单提交监听
                        form.on('submit(affirm)', function (formData) {
                            //阻止重复提交
                            formData.elem.disabled = true;

                            console.log(formData.field)
                            if (formData.field.State == "1") {
                                formData.field.residueNum = -1;
                            }
                            console.log(formData.field)
                            $.ajax({
                                url: 'http://localhost:5174/api/RoomHousingState/UpdatePriceCalendar',
                                type: 'post',
                                contentType: "application/json",
                                data: JSON.stringify(formData.field),
                                success: function (res) {
                                    // 添加成功后的操作
                                    if (res.code > 0) {
                                        layer.msg("修改成功");
                                        show()
                                    }
                                },
                                error: function (error) {
                                    console.error(error);
                                }
                            });
                            layer.closeAll(); // 关闭所有弹出层
                            return false; // 阻止表单的默认提交
                        });
                    }
                });
            }

        });


        // 弹出层取消按钮
        $(document).on('click', '[lay-on="closeFormBtn"]', function () {
            layer.closeAll(); // 关闭所有弹出层
        });

        // 辅助函数：格式化日期为 MM/DD
        function formatDate(date) {
            var month = (date.getMonth() + 1).toString().padStart(2, '0');
            var day = date.getDate().toString().padStart(2, '0');
            return month + '/' + day;
        }

        // 辅助函数：获取日期对应的星期几
        function getWeekday(date) {
            var weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            return weekdays[date.getDay()];
        }

        // 获取当前日期并格式化为 yyyy-mm-dd
        function getCurrentDate() {
            const today = new Date();
            const yyyy = today.getFullYear();
            const mm = String(today.getMonth() + 1).padStart(2, '0'); // January is 0!
            const dd = String(today.getDate()).padStart(2, '0');
            return yyyy + '-' + mm + '-' + dd;
        }
    });
</script>